<template>
  <q-form ref="form" @submit="onSubmit" class="q-gutter-md q-pb-xl">
    <formInput ref='formInput' :fieldlist="formFields" multipleCol />

    <history v-if="mode === 'edit'" class="q-mb-xl" :data="historyData" :escape="historyEscape" :tableFields="tableFields" />

    <q-page-sticky position="bottom" :offset="[0, 28]">
      <q-btn label="保存" type="submit" color="primary" class="btn-fixed-width" icon="save" :loading="saving" v-if="canSave" />
      <q-btn label="返回" @click="onReset" color="primary" outline class="q-ml-md bg-white" />
    </q-page-sticky>
  </q-form>

  <!-- 选择任务对话框 -->
  <dialogSelectTable ref="taskDialog" :config="dialogConfig" size="lg"></dialogSelectTable>
</template>

<script>
import { defineComponent } from 'vue';
import formInput from 'src/components/FormInput.vue';
import { detailPageMix } from 'src/lib/mixin.js';
import history from 'src/components/history.vue'
import { isNumber } from 'src/lib/utils.js';
import { useMeta } from 'quasar';
import { useStore } from 'stores/store';
import dialogSelectTable from 'src/components/DialogSelectTable.vue';
import taskConfig from 'app/search/tenant/delivery/task.js';
import moment from 'moment';
import dialogForm from 'src/components/DialogInputForm.vue';

export default defineComponent({
  name: 'deliveryDetail',
  setup (props, context) {
    const $store = useStore();
    const modelLabel = '配送单';
    const moduleName = 'delivery';
    const detailApi = `/c2/tenant/${moduleName}/detail`; // 明细数据接口
    const createApi = `/c2/tenant/${moduleName}/create`; // 新建数据接口
    const updateApi = `/c2/tenant/${moduleName}/update`; // 更新数据接口
    const taskApi = `/c2/tenant/${moduleName}/task`; // 任务数据列表接口

    useMeta({
      // 设置文件标题
      title: `${modelLabel}详情 - ${$store.siteConfig.appName} - 木多鱼系列`
    });

    return {
      modelLabel,
      moduleName,
      detailApi,
      createApi,
      updateApi,
      taskApi
    }
  },
  components: {
    formInput,
    history,
    dialogSelectTable,
    dialogForm
  },
  mixins: [detailPageMix],
  inject: ['approveBox'],
  data () {
    const self = this;
    return {
      formFields: {
        bill_no: { type: 'input', label: '配送单号', value: '', hint: '若留空，系统会自动生成', readonly: false },
        consignee: { type: 'input', label: '联系人', value: '', readonly: false },
        tel: { type: 'input', label: '联系电话', value: '', readonly: false },
        address: { type: 'input', label: '地址', value: '', readonly: false },

        logistics: { type: 'autocomplete', label: '物流公司', value: '', dict: 'logistics', readonly: false },
        logistics_no: { type: 'input', label: '物流单号', value: '', readonly: false },
        delivery_fee: { type: 'input', label: '送货费', value: '', suffix: '元', rules: [val => (val === '' || isNumber(val)) || '请输入数值型数据'], readonly: false },

        remark: { type: 'input', label: '备注', value: '', autogrow: true, readonly: false },

        t_delivery_details: {
          type: 'table',
          label: '配送明细',
          value: [],
          editmode: ['edit', 'delete'],
          columns: [
            { name: 'id', field: 'id', visible: false, editConfig: {} },
            { name: 'sale_detail_uid', field: 'sale_detail_uid', visible: false, editConfig: {} },
            { name: 'material_unit', field: 'material_unit', visible: false, editConfig: {} },
            { name: 'sale_bill_no', label: '销售单号', field: 'sale_bill_no', align: 'center', editConfig: { type: 'input', value: '', readonly: true } },
            { name: 'type', label: '销售单类型', field: 'type', align: 'center', format: val => val && this.dictObj && this.dictObj.saleType && this.dictObj.saleType[val] && this.dictObj.saleType[val].label, editConfig: { type: 'select', value: '', dict: 'saleType', readonly: true } },
            { name: 'customer_name', label: '客户', field: 'customer_name', align: 'center', editConfig: { type: 'input', value: '', readonly: true } },
            { name: 'consumer_name', label: '消费者', field: 'consumer_name', align: 'center', editConfig: { type: 'input', value: '', readonly: true } },
            { name: 'material_image', label: '货物图片', field: 'material_image', isImage: true, align: 'center', editConfig: {} },
            { name: 'material_name_model', label: '货物', field: 'material_name_model', align: 'center', editConfig: { type: 'input', value: '', readonly: true } },
            { name: 'sale_amount', label: '销售数量', field: 'sale_amount', align: 'center', format: (val, row) => `${Number(val)} ${row.material_unit || ''}`, editConfig: { type: 'input', value: '', suffix: '{material_unit}', readonly: true } },
            {
              name: 'deliver_amount',
              label: '配送数量',
              field: 'deliver_amount',
              align: 'center',
              format: (val, row) => `${Number(val)} ${row.material_unit || ''}`,
              editConfig: {
                type: 'input',
                value: '',
                rules: [val => isNumber(val) || '请输入数值型数量'],
                suffix: '{material_unit}',
                readonly: false
              }
            },
            {
              name: 'remark',
              label: '配送备注',
              field: 'remark',
              align: 'center',
              editConfig: { type: 'input', value: '', autogrow: true, readonly: false }
            }
          ],
          btn: {
            label: '从任务添加',
            fn () {
              self.$refs.taskDialog.show().then(res => {
                if (res && res.length > 0) {
                  for (const row of res) {
                    let canAdd = true;
                    if (!self.formFields.t_delivery_details.value) self.formFields.t_delivery_details.value = [];

                    if (self.formFields.t_delivery_details.value && self.formFields.t_delivery_details.value.length > 0) {
                      canAdd = self.formFields.t_delivery_details.value.filter(v => v.sale_detail_uid == row.uid).length === 0;
                    }
                    if (canAdd) {
                      self.formFields.t_delivery_details.value.push(self.matchTaskData(row));
                    }
                  }
                }
              });
            }
          }
        }
      },
      dialogConfig: {
        title: '选择任务',
        api: this.taskApi,
        search: {
        },
        table: {
          columns: [
            { name: 'bill_no', label: '销售单号', field: 'bill_no', sortable: true, align: 'center' },
            { name: 'type', label: '销售单类型', field: 'type', sortable: true, align: 'center', format: val => val && this.dictObj && this.dictObj.saleType && this.dictObj.saleType[val] && this.dictObj.saleType[val].label },
            { name: 'customer_name', label: '客户', field: 'customer_name', sortable: true, align: 'center' },
            { name: 'consumer_name', label: '消费者', field: 'consumer_name', sortable: true, align: 'center' },
            { name: 'material_name_model', label: '货物', field: 'material_name_model', sortable: true, align: 'center' },
            { name: 'sale_amount', label: '销售数量', field: 'sale_amount', sortable: true, align: 'center', format: (val, row) => `${Number(val)} ${row.material_unit || ''}` },
            { name: 'deliver_amount', label: '已配送数量', field: 'deliver_amount', sortable: true, align: 'center', format: (val, row) => `${Number(val)} ${row.material_unit || ''}` },
            { name: 'left_amount', label: '待配送数量', field: 'left_amount', align: 'center', format: (val, row) => `${Number(val)} ${row.material_unit || ''}`, classes: 'text-bold text-primary' },
            { name: 'consignee', label: '联系人', field: 'consignee', sortable: true, align: 'center' },
            { name: 'tel', label: '联系电话', field: 'tel', sortable: true, align: 'center' },
            { name: 'address', label: '地址', field: 'address', sortable: true, align: 'center' }
          ],
          multiple: true,
          key: 'id'
        }
      }
    };
  },
  async created () {
    this.assembly(taskConfig.search, this.dialogConfig.search); // 根据配置生成搜索条件
  },
  mounted () {
    if (this.mode === 'add') {
      this.fetchTask();
    } else if (this.mode === 'edit') {
      this.refreshData();
    }
  },
  methods: {
    async onSubmit () {
      if (!this.formFields.t_delivery_details.value || this.formFields.t_delivery_details.value.length < 1) {
        this.$q.notify({
          message: '明细不能为空',
          color: 'negative',
          icon: 'error',
          position: 'center',
          timeout: 5000
        });
        return;
      }
      const err = this.$refs.formInput.validateTable();
      if (err) {
        this.$q.notify({
          message: err,
          color: 'negative',
          icon: 'error',
          position: 'top',
          timeout: 2000
        });
        return;
      }

      this.$refs.formInput.validateAll();
      this.$nextTick(() => {
        this.$refs.form.validate().then(ot => {
          if (ot) {
            this.saving = true;
            this.$refs.formInput.getFormData().then(data => {
              this.saveData(data);
            }).catch(e => {
              console.log(e);
              this.saving = false
            });
          }
        });
      });
    },
    async fetchTask () {
      const taskIds = this.getTask(this.moduleName); // 从任务交换区取任务
      if (taskIds && taskIds.length > 0) { // 有任务，则去取数据
        const taskData = await this.getTaskData(taskIds);
        if (taskData.length > 0) {
          this.formFields.t_delivery_details.value = taskData.map(v => (this.matchTaskData(v)));
        }
      }
    },
    matchTaskData (row) {
      if (!this.formFields.consignee.value && row.consignee) {
        this.formFields.consignee.value = row.consignee;
        this.formFields.tel.value = row.tel;
        this.formFields.address.value = row.address;
      }

      return {
        id: null,
        sale_detail_uid: row.uid,
        sale_bill_no: row.bill_no,
        type: row.type,
        customer_name: row.customer_name,
        consumer_name: row.consumer_name,
        material_unit: row.material_unit,
        material_name_model: row.material_name_model,
        material_image: row.material_image,
        sale_amount: row.sale_amount,
        sale_detail_remark: row.sale_detail_remark,
        deliver_amount: row.left_amount,
        remark: row.sale_detail_remark
      }
    }
  },
  computed: {
  },
  watch: {
  }
});
</script>
